﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace BuildHelper.Work.Tools.DataSetFix
{
    public static class DataSetFixTools
    {
        public static bool FixDataSetFile(string file)
        {
            bool result = false;
            if (File.Exists(file))
            {
                try
                {
                    Encoding e = ProgNetComponents.Tools.FileTools.GetFileEncoding(file);
                    string content = file.ReadFile();
                    var dic = content.GetMatches("ZOrder=\"(\\d*)\"");

                    int idx = 0;
                    int next;
                    string str;
                    int intIdx;
                    string newStr;
                    intIdx = 1;
                    foreach (var i in dic)
                    {
                        str = "ZOrder=\"" + i + "\"";
                        idx = content.IndexOf(str);
                        next = content.IndexOf(str, idx + 1);
                        while (next > -1)
                        {
                            while (dic.Contains(intIdx.ToString()))
                                intIdx++;

                            newStr = "ZOrder=\"" + intIdx + "\"";
                            intIdx++;
                            content = content.Remove(next, str.Length);
                            content = content.Insert(next, newStr);
                            next = content.IndexOf(str, next + 1);
                        }
                    }
                    content.WriteToFile(file, e, true);
                    result = true;
                }
                catch(Exception ex)
                {
                    ex.Log();
                }
            }
            return result;
        }

        public static void ShowFixDataSetDialog()
        {
            using (OpenFileDialog dlg = new OpenFileDialog())
            {
                dlg.Filter = "xss|*.xss";
                dlg.Title = "Wybierz plik xss";
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    if (FixDataSetFile(dlg.FileName))
                    {
                        FormMain.Instance.ShowDxInfoDialog("DataSet naprawiony.");
                    }
                    else
                    {
                        FormMain.Instance.ShowDxWarningDialog("Błąd naprawiania.");
                    }
                }
            }
        }
    }
}
